package com.hiwan.wechat.web;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hiwan.system.pojo.ReturnInfo;
import com.hiwan.system.pojo.UserInfo;
import com.hiwan.system.util.SHA1Utils;
import com.hiwan.wechat.enumeration.CorpAppInfoEnum;
import com.hiwan.wechat.pojo.NewsMessage;
import com.hiwan.wechat.pojo.NewsMessage.Article;
import com.hiwan.wechat.pojo.Ticket;
import com.hiwan.wechat.pojo.WxJsApiConfigInfo;
import com.hiwan.wechat.quartz.AccessTokenQuartz;
import com.hiwan.wechat.quartz.JsApiTicketQuartz;
import com.hiwan.wechat.service.PublishMessageService;
import com.hiwan.wechat.service.WechatService;
import com.hiwan.wechat.util.WechatRequestUrl;

@Controller
@RequestMapping("/wechat")
public class WechatAction {
//	@Autowired
//	private JsApiTicketQuartz jsApiTicketQuartz;
//	@Autowired
//	private AccessTokenQuartz accessTokenQuartz;
	/**
	 * 获取getJsApiConfigInfo
	 */
	@RequestMapping("mobile/getJsApiConfigInfo")
	public @ResponseBody Map<String,Object>  getJsApiConfigInfo(HttpServletRequest req, HttpServletResponse resp) {
		Map<String,Object> map=new HashMap<String,Object>();
		WxJsApiConfigInfo jsApiConfigInfo = new WxJsApiConfigInfo();
		try 
		{
			String pageUrl = req.getParameter("pageUrl");
			Ticket jsApiTicket = WechatService.getJsApiTicket(CorpAppInfoEnum.ProductMarket);
			
			long timestamp = Calendar.getInstance().getTimeInMillis() / 1000;
			
			String src_signature = "jsapi_ticket=" + jsApiTicket.getTicket() + 
									"&noncestr=" + WechatRequestUrl.nonceStr +
									"&timestamp=" + timestamp +
									"&url=" + pageUrl;
			
			System.out.println("src_signature > "+ src_signature);
			
			String signature = SHA1Utils.hex_sha1(src_signature);
			
			System.out.println("signature > "+ signature);
			
			jsApiConfigInfo.setAppId(WechatRequestUrl.CORP_ID);
			jsApiConfigInfo.setTimestamp(timestamp);
			jsApiConfigInfo.setNonceStr(WechatRequestUrl.nonceStr);
			jsApiConfigInfo.setSignature(signature);
			
			map.put("data", jsApiConfigInfo);
			map.put("retcode", "0");
			map.put("msg", "成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("retcode", "99");
			map.put("msg", "获取失败");
		}
		return map;
	}
	
	/**
	 * 获取userId
	 */
	@RequestMapping("mobile/getUserId")
	@ResponseBody
	public Map<String,Object>  getUserId(HttpServletRequest req, HttpServletResponse resp) {
		Map<String,Object> map=new HashMap<String,Object>();
		ReturnInfo resultObj = new ReturnInfo();
		try 
		{
			String code = req.getParameter("code");
			String agentid = req.getParameter("agentid");
			
			String userId = WechatService.getUserId(CorpAppInfoEnum.parse(agentid), code);
			resultObj.setResult(userId);
			if (StringUtils.isNotBlank(userId)){
				//成功设值 
				resultObj.setRetcode(0);
				resultObj.setRetmsg("成功");
			}
			map.put("data", resultObj);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("data", resultObj);
		}
		return map;
	}
	/**
	 * 获取企业用户信息,本次返回用户头像
	 */
	@RequestMapping("mobile/getQyUserInfo")
	@ResponseBody
	public Map<String,Object>  getQyUserInfo(HttpServletRequest req, HttpServletResponse resp) {
		Map<String,Object> map=new HashMap<String,Object>();
		ReturnInfo resultObj = new ReturnInfo();
		try 
		{
			String userId = req.getParameter("userId");
			String avatar = WechatService.getQyUserInfo(CorpAppInfoEnum.ProductMarket, userId);
			resultObj.setResult(avatar);
			if (StringUtils.isNotBlank(userId)){
				//成功设值 
				resultObj.setRetcode(0);
				resultObj.setRetmsg("成功");
			}
			map.put("data", resultObj);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("data", resultObj);
		}
		return map;
	}
	/**
	 * 获取openId和用户头像（无法获取，弃用）
	 */
//	@RequestMapping("mobile/getUserInfo")
//	@ResponseBody
//	public Map<String,Object>  getOpenId(HttpServletRequest req, HttpServletResponse resp) {
//		Map<String,Object> map=new HashMap<String,Object>();
//		ReturnInfo resultObj = new ReturnInfo();
//		try 
//		{
//			String userId = req.getParameter("userId");
//			userId="{\"userid\": \"20170307\"}";
//			String accessToken=AccessTokenQuartz.getAccessToken().getToken();
//			String openId = WechatService.getOpenId(accessToken, userId);
//			UserInfo u = WechatService.getUserInfo(accessToken, openId);
//			resultObj.setResult(u);
//			//成功设值 
//			resultObj.setRetcode(0);
//			resultObj.setRetmsg("成功");
//			map.put("data", resultObj);
//		} catch (Exception e) {
//			e.printStackTrace();
//			map.put("data", resultObj);
//		}
//		return map;
//	}
	/**
	 * 发消息
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("sendMsg")
	@ResponseBody
	public void sendMsg(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
		String userId=req.getParameter("userId");
		List<String> tousers=new ArrayList<String>();
		tousers.add(userId);
		publshMsg(tousers);
	}
	/**
	 * 
	 * @param userId
	 * @throws UnsupportedEncodingException 
	 */
	public void publshMsg(List<String> tousers) throws UnsupportedEncodingException
	{
		/**
		 * 构建发送内容
		 */
		List<Article> articles = new ArrayList<Article>();
			NewsMessage newsMsg = new NewsMessage();
			Article article = newsMsg.new Article();
			article.setTitle("测试");
			article.setPicurl("http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E6%9F%AF%E5%8D%97&step_word=&hs=0&pn=18&spn=0&di=120486204850&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=2&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=1403090949%2C1510637804&os=3948369312%2C3652653176&simid=3413431336%2C4237247030&adpicid=0&lpn=0&ln=1970&fr=&fmq=1506045013952_R&fm=result&ic=0&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fm.haote.com%2Fupload%2Fzhuanti%2F20160627%2F1467029494640320.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Biw5pj_z%26e3Bv54AzdH3Fzi7wgptAzdH3Fzw54jg2xty57_z%26e3Bip4s%3F_p_p_p%3Da_z%26e3Bbamdn8nm09a800b0&gsm=0&rpstart=0&rpnum=0");
			article.setDescription("测试");
			// 消息链接地址
			String url = WechatRequestUrl.oauth_url.replace("REDIRCTURL", URLEncoder.encode("http://www.baidu.com", "UTF-8"));
			article.setUrl(url);
			articles.add(article);
			/**
			 * 调用接口向微信发推送消息
			 */
		PublishMessageService.publishExamToUsers(WechatService.getAccessToken(CorpAppInfoEnum.ProductMarket).getToken(), 59, false, tousers, articles);
	}
//	/**
//	 * 获取网页access_token以及用户openid
//	 * @param shareInfo
//	 * @return
//	 */
//	@RequestMapping("getOpenId")
//	public @ResponseBody Map<String, Object> getOpenId(String code){
//		Map<String, Object> map = new HashMap<String, Object>();
//		try {
//			WechatUserInfoVO wechatUserInfo = WechatService.getWechatOpenId(code);
//			if(wechatUserInfo!=null){
//				map.put("retcode", "0");
//				map.put("retmsg", "获取openid成功");
//				map.put("data", wechatUserInfo);
//			}else{
//				map.put("retcode", "1");
//				map.put("retmsg", "获取openid失败");
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			map.put("retcode", "99");
//			map.put("retmsg", "获取openid异常");
//		}
//		return map;
//	}
}
